import sys
import pdb
import threading
import heartbeating
import MSSafeinsideLib as lib
log = lib.MSLogger.get('device_transfer_mon', True)
g_name = 'ms device transfer monitor'

log.info(g_name + ' starting as %s' % (str(sys.argv)))

try:
    pass
    #heartbeat = heartbeating.HeartbeatListener(8090)
    #heartbeat.start()
except Exception, err:
    log.error('code: %s', str(err))
    sys.exit(1)

def processNormalObjects(isTerminated, dummy):
    log.info('processNormalObjects: started')

    try:
        cfg = lib.MSConfig.getConfig()
        reader = lib.MSDBReader(cfg.get('msdb', 'host'),
                                cfg.get('msdb', 'port'),
                                cfg.get('msdb', 'dbname'),
                                cfg.get('msdb', 'user'),
                                cfg.get('msdb', 'pwd'))
        reader.connect()

    except Exception, err:
        log.info('processNormalObjects: can\'t start: %s', str(err))
        return

    objects = [1553, 9]
    ctr = 0
    lastEventId = 0

    try:
        while not isTerminated.isSet():
            for msid in objects:
                try:
                    cursor = reader.connection.cursor()
                    query = "UPDATE [%s].[dbo].[_device_transfer] SET changeVoice='False' WHERE deviceId=%d" % (cfg.get('msdb', 'dbname'), msid)
                    cursor.execute(query)
                except Exception,err:
                    log.error('processNormalObjects: error: %s' % (str(err)))
                reader.connection.commit()
                lib.time.sleep(40)
    except Exception, err:
        log.error('processNormalObjects: fatal error: %s' % (str(err)))

log.info('starting threads... ')
isTerminated = threading.Event()
isTerminated.clear()

normalObjectsFromMSDB   = threading.Thread(target=processNormalObjects, name='normalObjectsFromMSDB', args=(isTerminated, None))
try:
    #start them
    normalObjectsFromMSDB.start()
    #check them
    lib.time.sleep(5)
    if not normalObjectsFromMSDB.isAlive(): raise RuntimeError('normalObjectsFromMSDB is not alive')
except Exception, err:
    log.error('can\'t start threads: ', str(err))
    sys.exit(2)

log.info(g_name + ' started. Waiting for stop signal...')
try:
    while True: lib.time.sleep(10)
except KeyboardInterrupt:
    log.info(g_name + ' stopping: %s' % (str(sys.argv)))
    sys.exit(0)
except Exception, err:
    log.error(g_name + ' stopping, fatal error: %s' % (str(err)))
    sys.exit(5)
finally:
    try:
        isTerminated.set()
        normalObjectsFromMSDB.join()
        heartbeat.stop()
        log.info('stopped')
    except Exception, err:
        log.error('error while exiting: %s', str(err))
        sys.exit(4)
